﻿using System;
using System.Collections.ObjectModel;
using System.Data.SQLite;
using System.Windows;
using System.Windows.Controls;
using WpfApp1.ViewModel;

namespace WpfApp1.View
{
    /// <summary>
    /// Schedule.xaml 的交互逻辑
    /// </summary>
    public partial class Schedule : Window
    {
        private static ObservableCollection<Model.Schedule> globalSchedules;
        public Schedule()
        {
            InitializeComponent();
            ScheduleViewModel scheduleViewModel = new ScheduleViewModel();
            schedule_list.DataContext = scheduleViewModel.Schedules;
            globalSchedules = scheduleViewModel.Schedules;
        }

        private void AddNew(object sender, AddingNewItemEventArgs e)
        {

        }

        private void InitNew(object sender, InitializingNewItemEventArgs e)
        {

        }

        // 编辑后
        private void Schedule_list_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            Model.Schedule schedule = e.Row.Item as Model.Schedule;
            DateTime novalue;
            if (e.Column.Header.ToString() == "日期" && !DateTime.TryParse(schedule.Time, out novalue))
            {
                MessageBox.Show("日期格式不正确，应该为 xxxx-xx-xx 或 xxxx/xx/xx");
                return;
            }
            if (schedule.Id == 0)
            {
                string sql_insert = "insert into schedules (title,time,type,pre_intervals,created_at) values (\"" + schedule.Title + "\",\"" + schedule.Time + "\",0," + schedule.Pre_intervals + ",\"" + System.DateTime.UtcNow.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss") + "\")";
                SQLiteCommand command = new SQLiteCommand(sql_insert, MainWindow.connection);
                command.ExecuteNonQuery();
                string sql_new_id = "select last_insert_rowid() from schedules";
                command = new SQLiteCommand(sql_new_id, MainWindow.connection);
                long id = (long)command.ExecuteScalar();
                schedule.Id = id;
            }
            else
            {
                string sql_update = "update schedules set title=\"" + schedule.Title + "\",time=\"" + schedule.Time + "\",pre_intervals=" + schedule.Pre_intervals + " where id=" + schedule.Id;
                SQLiteCommand command = new SQLiteCommand(sql_update, MainWindow.connection);
                command.ExecuteNonQuery();
            }
        }

        private void InitList()
        {
            schedule_list.DataContext = globalSchedules;
        }

        private void Del_Click(object sender, RoutedEventArgs e)
        {
            Model.Schedule schedule = schedule_list.SelectedItem as Model.Schedule;
            string sql_del = "delete from schedules where id=" + schedule.Id;
            SQLiteCommand command = new SQLiteCommand(sql_del, MainWindow.connection);
            command.ExecuteNonQuery();
        }
    }
}
